package com.aaa.sso.service;


import com.aaa.entity.BBusinessInfo;
import com.aaa.entity.UUserInfo;
import com.aaa.entity.UUserPermission;
import com.aaa.security.util.WebUtils;
import com.aaa.sso.feigen.BusinessInfoFegin;
import com.aaa.sso.feigen.PermissionFeigen;
import com.aaa.sso.feigen.UserInfoFeign;
import com.aaa.sso.vo.MyUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;


@Service
public class BusinessServiceAndUserService implements UserDetailsService {
    @Autowired
    private BusinessInfoFegin businessInfoFegin;
    @Autowired
     private   PermissionFeigen permissionFeigen;
    @Autowired
    private UserInfoFeign userInfoFeign;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        HttpServletRequest request = WebUtils.getRequest();
        String login_type = request.getParameter("login_Type");


        if("BUSINESS_PHONE".equals(login_type)) {
            //1.根据用户名查询用户信息
            BBusinessInfo businessInfo = businessInfoFegin.getByName(username);
            if (businessInfo != null) {
                //2.根据当前用户查询该用户具有的权限。
                List<UUserPermission> permissions = permissionFeigen.businessInfoAll();
                Collection<SimpleGrantedAuthority> authorities = permissions.stream().map(item -> new SimpleGrantedAuthority(item.getPname())).collect(Collectors.toList());
                MyUser user = new MyUser(businessInfo.getTelephone(), businessInfo.getPassword(), authorities, "BUSINESS_PHONE",businessInfo.getId());
                user.setLoginType(login_type);
                return user;
            }
        }else if("USER_PHONE".equals(login_type)) {
            //1.根据用户名查询用户信息
            UUserInfo userInfo = userInfoFeign.getByName(username);

            if (userInfo != null) {

                //2.根据当前用户查询该用户具有的权限。
                List<UUserPermission> permissions = permissionFeigen.getPermissionByUserid();
                Collection<SimpleGrantedAuthority> authorities = permissions.stream().map(item -> new SimpleGrantedAuthority(item.getPname())).collect(Collectors.toList());
                MyUser user = new MyUser(userInfo.getTelephone(), userInfo.getPassword(), authorities, "USER_PHONE",userInfo.getId());
                user.setLoginType(login_type);
                return user;
            }
        }
        return null;
    }
}






















